package com.msb.common.exception;

/**
 * @Author zhangjiajun
 * @Email zhangjiajun@hydsoft.com
 * @Description
 * @Date 2025/6/19 9:16
 */

import com.msb.common.utils.R;
import lombok.extern.slf4j.Slf4j;
import org.springframework.validation.FieldError;
import org.springframework.web.bind.MethodArgumentNotValidException;
import org.springframework.web.bind.annotation.ExceptionHandler;
import org.springframework.web.bind.annotation.RestControllerAdvice;

import java.util.HashMap;
import java.util.List;
import java.util.Map;

/**
 * 统一异常处理类
 */
@Slf4j
@RestControllerAdvice(basePackages = "com.msb.mall.producet.controller")
public class ExceptionControllerAdvice {

    /**
     * 处理验证异常的方法
     *
     * @param e
     */
    @ExceptionHandler(value = MethodArgumentNotValidException.class)
    public R handleValidException(MethodArgumentNotValidException e) {
        Map<String, String> map = new HashMap<>();
        //获取非法字段
        List<FieldError> fieldErrors = e.getFieldErrors();
        for (FieldError fieldError : fieldErrors) {
            map.put(fieldError.getField(), fieldError.getDefaultMessage());
        }
        //return R.error(400, "提交的数据不合法!").put("data", map);
        return R.error(BizCodeEnume.VALID_EXCEPTION.getCode(), BizCodeEnume.VALID_EXCEPTION.getMsg()).put("data", map);
    }

    /**
     * 处理其他异常的方法
     *
     * @param e
     */
    @ExceptionHandler(value = Throwable.class)
    public R handlerException(Throwable e) {
        log.error("错误信息: {}", e.getMessage(), e);
        //return R.error(400, "未知异常信息!").put("data", e.getMessage());
        return R.error(BizCodeEnume.UNKNOW_EXCEPTION.getCode(), BizCodeEnume.UNKNOW_EXCEPTION.getMsg()).put("data", e.getMessage());

    }
}
